import {message, Space} from 'antd';
import {
  BookOutlined,
  CommentOutlined,
  NotificationOutlined,
  QuestionCircleOutlined
} from '@ant-design/icons';
import React, {useState} from 'react';
import { useModel, SelectLang } from 'umi';
import Avatar from './AvatarDropdown';
import Joyride from 'react-joyride';
import styles from './index.less';
import moment from "moment";
import NoticeIcon from "@/components/NoticeIcon/NoticeIcon";
import {history} from "@@/core/history";
import {init} from "@/utils/WebSocketUtil";
import {clearAllMsg, saveMsg} from "@/utils/globalService";
import {show} from "@/utils/NotificationUtil";

export type SiderTheme = 'light' | 'dark';

const steps = [
  {
    target: '.questionIcon',
    content: '这里是查看帮助！',
    event: 'hover',
    placement: 'auto'
  },
  {
    target: '.userInfo',
    content: '这里是个人中心及设置!',
    event: 'hover',
    placement: 'auto'
  },
  {
    target: '.chgLang',
    content: '这里可以切换语言!',
    event: 'hover',
    placement: 'auto'
  },
  {
    target: '.noticeMessage',
    content: '这里可以查看消息通知!',
    event: 'hover',
    placement: 'auto'
  },
  {
    target: '.ant-menu',
    content: '这里是菜单!',
    event: 'hover',
    placement: 'auto'
  }
];

const GlobalHeaderRight: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [joyrideVisible, setJoyrideVisible] = useState<boolean>(false);

  const showJoyride = () => {
    setJoyrideVisible(true);
  }

  if (!initialState?.currentUser) {
    return null;
  }

  if (initialState.currentUser && (moment(new Date()).format('YYYY-MM-DD') == moment(initialState.currentUser.createTime).format('YYYY-MM-DD'))){
    showJoyride();
  }

  document.addEventListener("visibilitychange", () => {
    // 页面变为不可见时触发
    if (document.visibilityState == 'hidden') {
      document.title = '燕子！没有你我可怎么活啊。。。';
    }
    // 页面变为可见时触发
    if (document.visibilityState == 'visible') {
      document.title = '欢迎回来';
    }
    if (!window.socket){
      init(initialState.currentUser.loginName);
    }
  });

  if (!window.socket){
    init(initialState.currentUser.loginName);
  }
  const socket = window.socket;
  //获得消息事件
  socket.onmessage = function(msg) {
    if (msg.data == null || msg.data == '' || msg.data == '连接成功'){
      return;
    }
    const res = msg.data.split('：');
    if (res[0].indexOf('notOnline') > -1){
      let name = res[0].split('_')[0];
      let param = name + "_" + res[1];
      saveMsg({msg: param});
      return;
    }
    let messages = initialState.currentUser.message || [];
    let notifications = initialState.currentUser.notification || [];
    let events = initialState.currentUser.event || [];
    const result = res[1].split('-');
    const type = result[0];
    const link = result[1];
    const content = result[2];

    if (type == 'message'){
      messages.push({
        id: messages.length + 1,
        avatar: <CommentOutlined style={{ color: 'orangered', cursor: 'pointer' }}/>,
        title: content,
        link: link,
        datetime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
        type: type,
      })
    }
    if (type == 'notification'){
      notifications.push({
        id: notifications.length + 1,
        avatar: <NotificationOutlined style={{ color: 'skyblue', cursor: 'pointer' }}/>,
        title: content,
        link: link,
        datetime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
        type: type,
      })
    }
    if (type == 'event'){
      events.push({
        id: events.length + 1,
        avatar: <BookOutlined style={{ color: 'green', cursor: 'pointer' }}/>,
        title: content,
        link: link,
        datetime: moment(new Date()).format('YYYY-MM-DD HH:mm:ss'),
        type: type,
      })
    }
    // setTotal(messages.length + notifications.length + events.length);
    //接受到消息后保存至全局state中
    setInitialState({
      ...initialState,
      currentUser: {
        ...initialState.currentUser,
        message: messages,
        notification: notifications,
        event: events
      }
    });
  };

  const clearMsg = (title: string) => {
    let key = '';
    switch (title) {
      case '消息':
        key = 'messageList'
        setInitialState({
          ...initialState,
          currentUser: {
            ...initialState.currentUser,
            message: []
          }
        });
        break;
      case '通知':
        key = 'notificationList'
        setInitialState({
          ...initialState,
          currentUser: {
            ...initialState.currentUser,
            notification: []
          }
        });
        break;
      case '待办':
        key = 'eventList'
        setInitialState({
          ...initialState,
          currentUser: {
            ...initialState.currentUser,
            event: []
          }
        });
        break;
      default:
        break;
    }
    clearAllMsg({ type: key }).then(res => {
      if (res.status === 200){
        message.info('已清空所有' + title);
      }
    })
  }


  return (
    <>
      <Space className={styles.right}>
        <span
          className={`${styles.action} questionIcon`}
          onClick={showJoyride}
        >
          <QuestionCircleOutlined />
        </span>
        <Avatar />
        <SelectLang className={`${styles.action} chgLang`} />
        <NoticeIcon
          className={`noticeMessage`}
          count={(initialState.currentUser.message ? initialState.currentUser.message.length : 0)+(initialState.currentUser.notification ? initialState.currentUser.notification.length : 0)+(initialState.currentUser.event ? initialState.currentUser.event.length : 0)}
          onItemClick={(item) => {
            history.push(item.link);
          }}
          onClear={(title: string, key: string) => clearMsg(title)}
          loading={false}
          clearText="清空"
          viewMoreText="查看更多"
          onViewMore={() => {show('功能正在开发中...', '', 'success')}}
          clearClose
        >
          <NoticeIcon.Tab
            tabKey="message"
            count={initialState.currentUser.message && initialState.currentUser.message.length || 0}
            list={initialState.currentUser.message && initialState.currentUser.message}
            title="消息"
            emptyText="您已读完所有消息"
            showViewMore
          />
          <NoticeIcon.Tab
            tabKey="notification"
            count={initialState.currentUser.notification && initialState.currentUser.notification.length || 0}
            list={initialState.currentUser.notification && initialState.currentUser.notification}
            title="通知"
            emptyText="你已查看所有通知"
            showViewMore
          />
          <NoticeIcon.Tab
            tabKey="event"
            title="待办"
            emptyText="你已完成所有待办"
            count={initialState.currentUser.event && initialState.currentUser.event.length || 0}
            list={initialState.currentUser.event && initialState.currentUser.event}
            showViewMore
          />
        </NoticeIcon>
      </Space>
      {
        joyrideVisible &&
        <div>
          <Joyride
            steps={steps}
            continuous={true} //使用next按钮顺序播放
            run={true}
            showProgress={true} //在按钮中显示进度
            showSkipButton={true} //显示跳过按钮
            spotlightClicks={true}  //聚光灯
            //设置自定义文字提示
            locale= {{ back: '返回', close: '关闭', last: '最后一个', next: '下一个', open: '打开', skip: '跳过' }}
          />
        </div>
      }
    </>
  );
};
export default GlobalHeaderRight;
